/*
 * PhotonRTOS础光实时操作系统 -- 串口驱动
 *
 * Copyright (C) 2022, 2023 国科础石(重庆)软件有限公司
 *
 * 作者: Xueming Dong <dongxueming@kernelsoft.com>
 *
 * License terms: GNU General Public License (GPL) version 3
 *
 */

#include <photon/init.h>
#include <photon/irq.h>
#include <asm/types.h>
#include <photon/printk.h>
#include <photon/console.h>
#include <asm/io.h>

typedef struct UART_t {
	volatile unsigned int DATA;
	volatile unsigned int STATE;
	volatile unsigned int CTRL;
	volatile unsigned int INTSTATUS;
	volatile unsigned int BAUDDIV;
} UART_t;

#define UART0_ADDR           ((UART_t *) (0x40004000))
#define UART_DR(baseaddr)    (*(unsigned int *) (baseaddr))

#define UART_STATE_TXFULL    (1 << 0)
#define UART_CTRL_TX_EN      (1 << 0)
#define UART_CTRL_RX_EN      (1 << 1)


static void uart_init(void)
{
	UART0_ADDR->BAUDDIV = 16;
	UART0_ADDR->CTRL = UART_CTRL_TX_EN;
}


static void mps2_uart_putc(unsigned char c)
{
	UART_DR(UART0_ADDR) = c;
}


static void mps2_simple_write(const uint8_t *s, uint32_t count)
{
	unsigned int i;

	for (i = 0; i < count; i++, s++) {
		if (*s == '\n')
			mps2_uart_putc('\r');
		mps2_uart_putc(*s);
	}
}


static int32_t mps2_init_simple(void)
{
	uart_init();

	return 0;
}


const struct simple_console global_simple_console = {
	.name  = "bsta1000R5",
	.init = mps2_init_simple,
	.write = mps2_simple_write,
};